package mao.thinkinjava.concurency.cyclebarrier;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author Totoro
 * @date 2020/6/1
 * @explain:
 */
public class Horse implements Runnable {
    private static int counter = 0;
    public static List<Horse> horses = new ArrayList<>();
    private static Random random = new Random(47);

    private int id = counter++;
    private int stride = 0;
    private static CyclicBarrier barrier;


    public Horse(CyclicBarrier barrier) {
        this.barrier = barrier;
        horses.add(this);
    }

    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()){
            stride+=random.nextInt(3);
            try {
                barrier.await();
            }catch (InterruptedException e){
                e.printStackTrace();
                throw new RuntimeException(e);
            }catch (BrokenBarrierException e){
                throw new RuntimeException(e);
            }
        }
    }

    public void summery(){
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < stride; i++) {
            builder.append("+");
        }
        builder.append(id);
        System.out.println(builder.toString());
    }

    @Override
    public String toString() {
        return "Horse{" +
                "id=" + id +
                ", stride=" + stride +
                '}';
    }

    public int getStride() {
         return stride;
    }
}
